﻿using CommonTools;
using shop.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace shop.Bll.trade
{
    public class ShopBll:IPageBll<Wdtshop>
    {
        public string Title => "店铺";

        public bool EnableEditOnList => true;

        public bool EnableCreateOnList => true;

        public bool RefreshOnOpen => true;

        public Action<int> TurnPage { set; get; }
        public Wdtshop CopyItem(Wdtshop item)
        {
            if (item == null)
                return null;

            var newItem = item.Clone();
            newItem.id = 0;
            newItem.isdel = false;

            return newItem;
        }

        public Wdtshop CreateItem()
        {
            return new Wdtshop() { isdel = false, FTime = DateTime.Now, };
        }

        public async Task<Result> DeleteItem(int id)
        {
            await DB.FSql.Update<Wdtshop>()
                .Where(a => a.id == id && a.isdel == false)
                .Set(a => a.isdel, true)
                .ExecuteAffrowsAsync();


            return new Result(true);
        }


        public async Task<Result<int>> EditCell(string dataPropertyName, object value, Wdtshop data)
        {
            if (data.id == 0)
            {
                data.FTime = await DB.FSql.GetTimeAsync();
                data.isdel = false;
                
                var nid = await DB.FSql.Insert(data)
                    .ExecuteIdentityAsync();

                data.id = (int)nid;
            }

            var dict = new Dictionary<string, object> { [dataPropertyName] = value };



            var dbRes = await DB.FSql.Update<Wdtshop>()
                .Where(a => a.id == data.id && a.isdel == false)
                .SetDto(dict)
                .ExecuteAffrowsAsync();

            return new Result<int>(true, "!", data.id);
        }

        public IEnumerable<DeclareColumn> GetColumns()
        {
            return new[]
            {
                new DeclareColumn(nameof(Wdtshop.id),"id"){ Visible= false},
                new DeclareColumn(nameof(Wdtshop.shop_name),"店铺名称"){ Width=300},
                new DeclareColumn(nameof(Wdtshop.shop_no),"店铺编号"){ Width=120},
                new DeclareColumn(nameof(Wdtshop.plat),"平台"){ Width=150 },
                new DeclareColumn(nameof(Wdtshop.FTime),"登记时间"){Width=110, ReadOnly= true},
            };
        }

        public async Task<Wdtshop> GetItem(int id)
        {
            return await DB.FSql.Select<Wdtshop>()
                .Where(a => a.isdel == false && a.id == id)
                .ToOneAsync();
        }


        #region 查询参数

        private string _shop;
        private string _shop_no;
        private string _plat;

        #endregion

        /// <summary> 查询ui </summary>
        public virtual ControlBuilder GetUIBuilder()
        {
            return new ControlBuilder()
                .Add<string>(ControlEnum.guanTextBox, "店铺名称", c => _shop = c)
                .Add<string>(ControlEnum.guanTextBox, "店铺编号", c => _shop_no = c)
                .Add<string>(ControlEnum.guanTextBox, "平台", c => _plat= c)
                .AddQueryButton("查询");
        }

        /// <summary> 查询 </summary>
        public async Task<PageQueryResult<Wdtshop>> QueryPage(DocFilterParameter queryPara)
        {
            var list = await DB.FSql.Select<Wdtshop>()
                .Where(a => a.isdel == false)
                .WhereIf(!string.IsNullOrEmpty(_shop), a => a.shop_name.Contains(_shop))
                .WhereIf(!string.IsNullOrEmpty(_shop_no), a => a.shop_no.Contains(_shop_no))
                .WhereIf(!string.IsNullOrEmpty(_plat), a => a.plat.Contains(_plat))
                .Page(queryPara.PageNo, queryPara.PageSize)
                //.OrderByDescending(a => a.shopGroup)
                .Count(out var c)
                .ToListAsync();

            return new PageQueryResult<Wdtshop>(true, null, list, c);
        }



        public async Task<Result> SaveItem(Wdtshop item)
        {
            if (item == null)
            {
                return new Result(false, "系统错误");
            }

            string err = string.Empty;
            if (string.IsNullOrEmpty(item.shop_name))
            {
                err += "店铺名称不能为空!";
            }

            if (string.IsNullOrEmpty(err) == false)
            {
                return new Result(false, err);
            }

            item.isdel = false;
            item.FTime = await DB.FSql.GetTimeAsync();

            if (item.id <= 0)
            {
                var id = await DB.FSql.Insert(item)
                    .ExecuteIdentityAsync();

                item.id = (int)id;
            }
            else
            {
                await DB.FSql.Update<Wdtshop>()
                    .SetSource(item)
                    .ExecuteAffrowsAsync();
            }

            return new Result(true);
        }


        public async Task<Result> SaveItem(IEnumerable<Wdtshop> items)
        {
            if (items == null)
            {
                return new Result(false, "系统错误");
            }

            var time = await DB.FSql.GetTimeAsync();

            foreach (var item in items)
            {
                item.isdel = false;
                item.FTime = time;
            }

            await DB.FSql.Insert(items).ExecuteAffrowsAsync();

            return new Result(true);

        }




        public async Task<IEnumerable<Wdtshop>> Query(string find)
        {
            var list = await DB.FSql.Select<Wdtshop>()
                .Where(a => a.isdel == false)
                .WhereIf(!string.IsNullOrEmpty(find), a => a.shop_name.Contains(find) || a.shop_no.Contains(find))
                .ToListAsync();

            return list;
        }





        public async Task<Result<object>> Save(Wdtshop info)
        {
            if (info == null)
            {
                return new Result<object>(false, "系统错误");
            }

            string err = string.Empty;

            if (string.IsNullOrEmpty(info.shop_name))
            {
                err = "店铺名称不过为空";
            }


            if (!string.IsNullOrEmpty(err))
            {
                return new Result<object>(false, err);
            }

            var bl = await DB.FSql.Select<Wdtshop>().
                Where(a => a.isdel == false && a.shop_name == info.shop_name
                       && a.id != info.id)
                   .AnyAsync();

            if (bl)
            {
                return new Result<object>(false, "名称重复,不能使用!");
            }


            if (info.id <= 0)
            {
                var id = await DB.FSql.Insert(info).ExecuteIdentityAsync();

                info.id = (int)id;
            }
            else
            {
                info.isdel = false;

                await DB.FSql.Update<Wdtshop>()
                    .SetSource(info)
                    .ExecuteAffrowsAsync();

            }
            return new Result<object>(true, info.id.ToString(), info.id);
        }


        public async Task<Result<object>> Delete(int id)
        {
            await DB.FSql.Update<Wdtshop>()
               .Where(a => a.id == id)
               .Set(a => a.isdel, true)
               .ExecuteAffrowsAsync();

            return new Result<object>(true);
        }

        /// <summary> 同步到服务器 </summary>
        public async Task SyncTo(List<Wdtshop> list)
        {
            var ids = list.Select(a => a.shop_no).ToArray();
            var old = await DB.FSql.Select<Wdtshop>()
                .Where(a => a.isdel == false && ids.Contains(a.shop_no))
                .ToListAsync();

            var time = await DB.FSql.GetTimeAsync();

            var updateList = new List<Wdtshop>();
            foreach (var item in old)
            {
                var find = list.FirstOrDefault(a => a.shop_no == item.shop_no);
                if (find != null)
                {
                    find.id = item.id;
                    find.FTime = time;

                    updateList.Add(find);
                }
            }

            await DB.FSql.Update<Wdtshop>()
                .SetSource(updateList)
                //.IgnoreColumns(nameof(Wdtshop.), nameof(Wdtshop.ItemId), nameof(Wdtshop.Remarks), nameof(Wdtshop.LogiAcct))
                .ExecuteAffrowsAsync();

            //剩下的insert
            var newList = list.Where(a => updateList.Any(c => c.shop_no == a.shop_no) == false)
                .ToList();
            foreach (var item in list)
            {
                item.FTime = time;
            }

            await DB.FSql.Insert(newList)
                .ExecuteAffrowsAsync();


        }





        /// <summary> 从旺店通查询 </summary>
        public async Task<List<Wdtshop>>  QueryShopFromWdt()
        {
            var list = new List<Wdtshop>();

            int i = 0;
            while (true)
            {
                var client = new WdtApi("shop.php");
                client.AddParam("page_size", "100");
                client.AddParam("page_no", i.ToString());
                i++;

                var res = await client
                    .Post<shop.Model.shopResult>();

                if(res.code ==0 )
                {
                    if(res.shoplist.Any()== false)
                    {
                        break;
                    }

                    foreach (var item in res.shoplist)
                    {
                        if (_plats.Value.TryGetValue(item.platform_id, out var plat))
                        {
                            item.plat = plat;
                        }
                    }
                    list.AddRange(res.shoplist);
                }
                else
                {
                    break;
                }

            }

            return list;

        }


        private Lazy<Dictionary<int, string>> _plats = new Lazy<Dictionary<int, string>>( ()=> new Dictionary<int, string>()
        {
            
{0,	"线下"},
{1,	"淘宝"},
{2,	"淘宝分销"},
{ 3,	"京东"},
{ 4,	"拍拍"},
{ 5,	"亚马逊"},
{ 6,	"1号店"},
{ 7,	"当当"},
{ 8,	"库巴"},
{ 9,	"阿里巴巴"},
{ 10,	"ECShop"},
{ 11,	"麦考林"},
{ 12,	"V+"},
{ 13,	"苏宁易购"},
{ 14,	"唯品会"},
{ 15,	"易迅"},
{ 16,	"聚美"},
{ 17,	"口袋通（有赞）"},
{ 18,	"Hishop"},
{ 19,	"微铺宝"},
{ 20,	"美丽说"},
{ 21,	"蘑菇街"},
{ 22,	"贝贝网"},
{ 23,	"ECstore"},
{ 24,	"折800"},
{ 25,	"融e购"},
{ 26,	"穿衣助手"},
{ 27,	"楚楚街"},
{ 28,	"微盟旺店"},
{ 29,	"卷皮网"},
{ 30,	"顺丰嘿客"},
{ 31,	"飞牛网"},
{ 32,	"微店"},
{ 33,	"百度mall"},
{ 34,	"蜜芽宝贝"},
{ 35,	"明星衣橱"},
{ 36,	"善融商城"},
{ 37,	"速卖通"},
{ 38,	"萌店"},
{ 39,	"拼多多"},
{ 40,	"京东到家"},
{ 41,	"百度外卖"},
{ 42,	"美团外卖"},
{ 43,	"大众点评"},
{ 44,	"口碑外卖"},
{ 45,	"饿了么"},
{ 46,	"我买网"},
{ 47,	"人人店"},
{ 48,	"美囤妈妈"},
{ 49,	"91拼团"},
{ 50,	"网易考拉海购"},
{ 51,	"千米网"},
{ 52,	"特奢汇"},
{ 53,	"楚楚街拼团"},
{ 54,	"天猫企业购"},
{ 55,	"孩子王"},
{ 56,	"小红书"},
{ 57,	"格格家"},
{ 58,	"云集"},
{ 59,	"楚楚通"},
{ 60,	"返利网"},
{ 61,	"酒仙网"},
{ 62,	"平安好医生"},
{ 63,	"下厨房"},
{ 64,	"好食期"},
{ 65,	"大V店"},
{ 66,	"好衣库"},
{67,	"达令家"},
{68,	"爱库存"},
{69,	"放心购(抖店）"},
{70,	"每日一淘"},
{71,	"贝壳优品"},
{72,	"小米有品"},
{73,	"未来集市"},
{74,	"爱奇艺商城"},
{75,	"快手小店"},
{76,	"魔筷星选"},
{77,	"海拍客"},
{78,	"壹钱包"},
{79,	"每日优鲜"},
{80,	"网易严选"},
{81,	"多点"},
{82,	"天猫超市-盘货"},
{83,	"微信视频号"},
{84,	"娇兰佳人"},
{86,	"今日爆团"},
{87,	"阿里健康大药房"},
{88,	"必要商城"},
{89,	"腾讯枫页"},
{90,	"微信小商城"},
{91,	"快手金牛"},
{92,	"摩点"},
{93,	"易订货"},
{94,	"天猫国际直营（轻轨三号线）"},
{96,	"驿氪"},
{97,	"妈妈良品"},
{98,	"小芒电商"},
{99,	"卡美啦"},
{100,	"年丰大当家"},
{101,	"得物新平台"},
{102,	"考拉商家直发平台"},
{103,	"美团闪购"},
{104,	"新华书店网上商城"},
{105,	"云货优选平台"},
{106,	"零售通平台"},
{107,	"易久批平台"},
{108,	"腾讯惠聚平台"},
{109,	"小鹅拼拼平台"},
{110,	"度小店平台"},
{111,	"枫页小店"},
{112,	"丁香妈妈平台"},
{113,	"药师帮平台"},
{114,	"蜂雷平台"},
{115,	"SHEIN希音平台"},
{116,	"bilibili会员购平台"},
{117,	"群接龙平台"},
{118,	"招商银行掌上生活平台"},
{119,	"华为商城平台"},
{121,	"单创VTN平台"},
{122,	"天虹商城平台"},
{123,	"有路平台"},
{125,	"系统供销"},
{126,	"定制"},
{127,	"自有平台"},
{128,	"猫享-考拉自营"},
{129,	"东方福利网"},
{130,	"浦惠到家"},
{131,	"B+东方播麦"},
{134,	"闲鱼"},
{135,	"小亚通"},
{136,	"百度营销"},
{137,	"淘宝代打代发"},
{139,	"抖音供销"},
{140,	"顺联动力"},
{142,	"喵街"}

        });

    }
}
